package com.example.filter;

import com.example.util.SignatureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SignatureFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(SignatureFilter.class);

    private final boolean signatureEnabled;
    private final SignatureUtil signatureUtil;
    private final long signatureExpireTime;

    public SignatureFilter(boolean signatureEnabled, SignatureUtil signatureUtil, long signatureExpireTime) {
        this.signatureEnabled = signatureEnabled;
        this.signatureUtil = signatureUtil;
        this.signatureExpireTime = signatureExpireTime;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws java.io.IOException, javax.servlet.ServletException {

        if (!signatureEnabled) {
            // 如果签名验证已禁用，则直接继续过滤链
            logger.debug("签名验证已禁用，跳过签名验证");
            filterChain.doFilter(request, response);
            return;
        }

        // 处理签名验证逻辑
        String requestPath = request.getRequestURI();
        String signature = request.getHeader("X-Signature");
        String timestampHeader = request.getHeader("X-Timestamp");

        logger.info("处理请求: {} | 签名: {} | 时间戳: {}", requestPath, signature, timestampHeader);

        // 验证签名逻辑
        if (signature == null || timestampHeader == null || !validateSignature(request, signature, timestampHeader)) {
            logger.warn("签名无效或请求已过期: {}", requestPath);
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "无效签名或请求已过期");
            return;
        }

        logger.info("签名验证通过: {}", requestPath);
        filterChain.doFilter(request, response);
    }

    private boolean validateSignature(HttpServletRequest request, String signature, String timestampHeader) {
        try {
            long requestTime = Long.parseLong(timestampHeader);
            long currentTime = System.currentTimeMillis();

            // 检查签名时效
            if (Math.abs(currentTime - requestTime) > signatureExpireTime) {
                logger.warn("Request expired: {} | RequestTime: {} | CurrentTime: {}", request.getRequestURI(), requestTime, currentTime);
                return false;
            }

            // 生成签名数据
            String requestPath = request.getRequestURI();
            String requestMethod = request.getMethod();
            String data = requestPath + requestMethod + timestampHeader;

            // 验证签名
            boolean isValid = signatureUtil.validateSignature(data, signature);
            if (!isValid) {
                logger.warn("Signature validation failed for request: {}", requestPath);
            }
            return isValid;

        } catch (Exception e) {
            logger.error("Error validating signature for request: {}", request.getRequestURI(), e);
            return false;
        }
    }
}
